/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.simba.utils.tree;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author ngonga
 */
public class Node implements Comparable{

    String label;
    Node parent;

    public Node(String _label) {
        label = _label;
        parent = null;
    }

    /** Returns path from root to current node
     * 
     * @return Path from root to this node
     */
    public List<Node> getParents() {
        if (parent == null) {
            return new ArrayList();
        } else {
            List l = parent.getParents();
            l.add(parent);
            return l;
        }
    }

    public void setParent(Node n) {
        parent = n;
    }

    public boolean hasParent() {
        if (parent == null) {
            return false;
        } else {
            return true;
        }
    }

    public int getDistanceFrom(Node n) {
        List l1 = getParents();
        List l2 = n.getParents();
        if(n.equals(this)) return 0;
        if (l1.contains(n) || l2.contains(this)) {
            return Math.abs(l1.size() - l2.size());
        }

        
        if (!n.hasParent()) {
            return Integer.MAX_VALUE;
        }
        if (!hasParent()) {
            return Integer.MAX_VALUE;
        } else {
            int index = 0;
            while (index < l1.size() && index < l2.size()) {
                if (!l1.get(index).equals(l2.get(index))) {
                    break;
                } else {
                    index++;
                }
            }

            return (l1.size() + l2.size() - 2 * index + 2);
        }
    }

    @Override
    public String toString() {
        return label;
//        if(parent!=null)
//        return "("+label+", "+parent.label+")";
//        else return "("+label+", ROOT)";
    }

    public static void main(String args[]) {
        Node n1 = new Node("1");
        Node n2 = new Node("2");
        Node n3 = new Node("3");
        Node n4 = new Node("4");
        Node n5 = new Node("5");

        n4.setParent(n3);
        n5.setParent(n3);
        n2.setParent(n1);
        n3.setParent(n1);

        System.out.println(n1.getDistanceFrom(n4));
    }

    @Override
    public int compareTo(Object o) {
        Node n = (Node)o;
        return n.label.compareTo(label);
    }
}
